package com.unitd.frame.comm.utils.encrypt;

import com.unitd.frame.comm.exception.EncryptException;

import java.security.MessageDigest;
import java.util.Arrays;

/**
 * @author Hudan
 * @version 1.0
 * @desc SHA1 签名算法工具类
 * @filename SHA1.java
 * @copyright www.pactera.com.cn
 * @date 2016/10/27
 */
public class SHA1 {

	/**
	 * @desc 用SHA1算法生成安全签名
	 * @param token     票据
	 * @param timestamp 时间戳
	 * @param nonce     随机字符串
	 * @param encrypt   密文
	 * @return 安全签名
	 * @throws EncryptException {@link EncryptException}
	 */
	public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws EncryptException {
		try {
			String[] array = new String[]{token, timestamp, nonce, encrypt};

			/* 字符串排序 */
			StringBuilder sb = new StringBuilder();
			Arrays.sort(array);
			for (int i = 0; i < 4; i++) {
				sb.append(array[i]);
			}

			/* SHA1签名生成 */
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.update(sb.toString().getBytes());
			byte[] digest = md.digest();

			StringBuffer hexstr = new StringBuffer();
			String shaHex = "";
			for (int i = 0; i < digest.length; i++) {
				shaHex = Integer.toHexString(digest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexstr.append(0);
				}
				hexstr.append(shaHex);
			}

			return hexstr.toString();
		} catch (Exception e) {
			throw new EncryptException(EncryptException.ERROR_COMPUTE_SIGNATURE, e);
		}
	}
}